package cn.jason.org.service.impl;

import cn.jason.basic.service.impl.BaseServiceImpl;
import cn.jason.basic.util.PageList;
import cn.jason.org.domain.Department;
import cn.jason.org.domain.Employee;
import cn.jason.org.mapper.DepartmentMapper;
import cn.jason.org.query.DepartmentQuery;
import cn.jason.org.service.IDepartmentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

     @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        if(department.getParent() == null){
            dirPath = "/"+department.getId();
        }else{
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public PageList<Department> queryPage(DepartmentQuery query) {
        Long total = departmentMapper.queryCount(query);
        List<Department> rows = departmentMapper.queryData(query);
        return new PageList<Department>(total,rows);
    }


    @Override
    public List<Department> queryTree() {
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(), department);
        }
        List<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            if(tmp.getParent_id() == null){
                firstDepts.add(tmp);
            }else{
                Department parent = allDepts.get(tmp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }
}
